package cn.yuhh.controller;

import cn.yuhh.entity.Blog;
import cn.yuhh.serviec.IBlogService;
import cn.yuhh.serviec.ITagService;
import cn.yuhh.serviec.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class BlogController {

    @Autowired
    private IBlogService blogService;

    @Autowired
    private ITypeService typeService;

    @Autowired
    private ITagService tagService;


    @GetMapping("/blogs")
    public String blogs(@PageableDefault(size = 10, sort = {"id"}, direction = Sort.Direction.DESC) Pageable pageable, Model model) {
        model.addAttribute("blogs", blogService.findAll(pageable));
        model.addAttribute("types", typeService.listType(pageable));
        return "/admin/blogs";
    }

    @GetMapping("/blogs/input")
    public String blogsInput(Model model) {
        model.addAttribute("types", typeService.listType());
        model.addAttribute("tags", tagService.listTag());
        model.addAttribute("blog", new Blog());
        return "/admin/blogs-input2";
    }


    @GetMapping("/blogs/{id}/edit")
    public String blogsEdit(@PathVariable Long id, Model model) {
        model.addAttribute("types", typeService.listType());
        model.addAttribute("tags", tagService.listTag());
        Blog blog = blogService.getOne(id);
        blog.init();
        System.out.println(blog.getContent());
        model.addAttribute("blog", blog);
        return "/admin/blogs-input2";
    }

    @PostMapping("/blogs")
    public String blogSave(Blog blog, HttpSession session, RedirectAttributes attributes) {
        Long id = blog.getId();
        blog.setType(typeService.findById(blog.getType().getId()));
        blog.setTags(tagService.listTag(blog.getTagIds()));
        Blog b = new Blog();

        if (id == null) {
            b = blogService.save(blog);
        } else {
            b = blogService.updataBlog(id, blog);
        }

        if (b == null) {
            attributes.addFlashAttribute("message", "操作失敗");
        } else {
            attributes.addFlashAttribute("message", "操作成功");
        }


        return "redirect:/admin/blogs";
    }

}
